/*
 * krautchantasksendpost.cpp
 *
 *  Created on: Oct 7, 2011
 *      Author: anonovermind <anonovermind@gmail.com>
 */

#include "krautchanagent.h"
#include "krautchantasksendpost.h"
#include <boost/format.hpp>

namespace Wishmaster {

KrautchanTaskSendPost::KrautchanTaskSendPost(const PostDescriptor& post, const QString& captcha, Wishmaster2::Network::RequestManager* requestManager,
		const QString& msg, KrautchanAgent* agent) : TaskSendPost(post, captcha, requestManager, msg),
		m_post(post),
		m_captcha(captcha),
		m_agent(agent)
{

}

KrautchanTaskSendPost::~KrautchanTaskSendPost() {
}

ThreadId KrautchanTaskSendPost::threadId() const
{
	return m_post.parent_thread;
}

Wishmaster2::Network::RequestPtr KrautchanTaskSendPost::makeRequest(const PostDescriptor& post, const QString& captcha,
		Wishmaster2::Network::RequestManager* requestManager)
{
	QString plainboardname = post.board;
	plainboardname.remove('/');

	QString referer = m_agent->makeThreadLink(post.parent_thread);

	Wishmaster2::Network::Url url(boost::str(boost::format("http://%s/post") % post.parent_thread.chanName().toStdString()));
	Wishmaster2::Network::RequestPtr request = requestManager->createRequest(url);
	request->setParameter("http:referer", referer.toStdString());
	request->setParameter("http:method", "POST");

	request->setParameter(defaultedString(property("field1name").toString(), "internal_n").toStdString(), std::string(post.name.toUtf8().constData()));
	request->setParameter(defaultedString(property("field3name").toString(), "internal_s").toStdString(), std::string(post.topic.toUtf8().constData()));
	if(post.sage)
		request->setParameter("sage", "1");
	request->setParameter(defaultedString(property("field4name").toString(), "internal_t").toStdString(), std::string(post.text.toUtf8().constData()));

	if(post.attachments.count() > 0)
	{
		for(int i = 0; i < post.attachments.count(); i++)
		{
			m_agent->addAttachments(request, post.attachments.at(i), QString("file_%1").arg(i));
		}
	}

	request->setParameter("forward", "thread");
	request->setParameter("password", std::string(post.password.toUtf8().constData()));

	request->setParameter("board", std::string(plainboardname.toUtf8().constData()));
	if(post.parent_thread.threadNumericId())
		 request->setParameter("parent", std::string(post.parent_thread.threadStringId().toUtf8().constData()));

	m_request = request;

	return request;
}

void KrautchanTaskSendPost::onRequestDone()
{
	QByteArray arr(m_request->content()->data(), m_request->content()->size());
	emit result(this, arr, QString(m_request->contentType().c_str()));
}

QString KrautchanTaskSendPost::defaultedString(const QString& str, const QString& def)
{
	if(str.isEmpty())
		return def;
	return str;
}

} /* namespace Wishmaster */
